package cat.joronya.supermanager.service.htmlcleanerImpl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.util.Log;

import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.market.Player;
import cat.joronya.supermanager.service.MarketParser;

public class MarketParserImpl implements MarketParser 
{
	public ArrayList<Player> players;
	
	// players XPATH
	private static final String PLAYERS_XPATH = "//table[@background='gif/fondomercado3arriba.gif']";
	
	public long parse(String html, Integer jornada, String position) throws Exception 
	{
		long start = System.nanoTime();
		
		try
		{
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode node = cleaner.clean(html);

			NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));
			
			// cerquem les jugadors
			Object[] table = node.evaluateXPath(PLAYERS_XPATH);
			TagNode tagTable = (TagNode)table[0];
			TagNode tagTbody = tagTable.getChildTags()[0];
			// llistem els jugados, diferents trs
			int i=0;
			for(Object objTr: tagTbody.getChildren())
			{
				// descartem dos primers tr dels headers
				if( i++ < 2 )
					continue;

				// els tds
				List tds = ((TagNode)objTr).getChildren();

				// inicialitzem player
				Player p = new Player();
				
				// setejem la jornada
				p.setDay(jornada);

				try
				{
					// segon td
					TagNode td1 = (TagNode) tds.toArray()[1];
					for (Object td1Child : td1.getChildren()) {
						TagNode img = (TagNode) td1Child;
						if ("img".equals(img.getName())) {
							String src = img.getAttributeByName("src");
							if ("gif/lesion.gif".equals(src))
								p.setStatus("lesio.png");
							if ("gif/baja.gif".equals(src))
								p.setStatus("baixa.png");

							break;
						}
					}

					// tercer td
					TagNode td2 = (TagNode) tds.toArray()[2];
					for (Object td2Child : td2.getChildren()) {
						TagNode img = (TagNode) td2Child;
						if ("img".equals(img.getName())) {
							String src = img.getAttributeByName("src");
							if ("gif/nacional.gif".equals(src))
								p.setNacionality("nacional.png");
							if ("gif/extra.gif".equals(src))
								p.setNacionality("extra.png");

							break;
						}
					}

					// quart td
					TagNode td3 = (TagNode) tds.toArray()[3];
					for (Object td3Child : td3.getChildren()) {
						TagNode a = (TagNode) td3Child;
						if ("a".equals(a.getName())) {
							String href = a.getAttributeByName("href");
							String cod = href
									.replace(
											"http://www.acb.com/stspartidojug.php?cod_jugador=",
											"");
							p.setCodi(cod);
							Log.d(Supermanager.TAG, "MarketParserImpl parsing code player: " + cod
									+ ", jornada: " + jornada);

							for (Object aChild : a.getChildren()) {
								TagNode font = (TagNode) aChild;
								if ("font".equals(font.getName())) {
									for (Object fontChild : font.getChildren()) {
										if (fontChild instanceof ContentNode) {
											String name = fontChild.toString();
											p.setName(name);
											break;
										}
									}
									break;
								}
							}
							break;
						}
					}

					// cinque td
					TagNode td4 = (TagNode) tds.toArray()[4];
					for (Object td4Child : td4.getChildren()) {
						// saltem espais inicials
						if (td4Child instanceof ContentNode)
							continue;

						TagNode a = (TagNode) td4Child;
						if ("a".equals(a.getName())) {
							String on = a.getAttributeByName("onMouseover");
							String info = on.replace("ddrivetip('", "").replace(
									"')", "");
							p.setInfo(info);

							break;
						}
					}

					// sise td
					TagNode td5 = (TagNode) tds.toArray()[5];
					for (Object td5Child : td5.getChildren()) {
						if (td5Child instanceof ContentNode) {
							String team = td5Child.toString().trim();
							p.setTeam(team);
							break;
						}
					}

					// sete td
					TagNode td6 = (TagNode) tds.toArray()[6];
					for (Object td6Child : td6.getChildren()) {
						if (td6Child instanceof ContentNode) {
							String balance = td6Child.toString().trim();
							p.setBalance(balance);
							break;
						}
					}

					// vuite td
					TagNode td7 = (TagNode) tds.toArray()[7];
					for (Object td7Child : td7.getChildren()) {
						if (td7Child instanceof ContentNode) {
							Float average;
							try {
								average = Float.valueOf(nf.parse(
										td7Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								average = Float.valueOf("0");
							}

							p.setAverage(average);
							break;
						}
					}

					// nove td
					TagNode td8 = (TagNode) tds.toArray()[8];
					for (Object td8Child : td8.getChildren()) {
						if (td8Child instanceof ContentNode) {
							Integer price;
							try {
								price = Integer.valueOf(nf.parse(
										td8Child.toString().trim()).intValue());
							} catch (ParseException pe) {
								price = Integer.valueOf(0);
							}
							p.setPrice(price);
							break;
						}
					}

					// dese td
					TagNode td9 = (TagNode) tds.toArray()[9];
					for (Object td9Child : td9.getChildren()) {
						if (td9Child instanceof ContentNode) {
							String minutes = td9Child.toString().trim();
							p.setMinutes(minutes);
							break;
						}
					}

					// onze td
					TagNode td10 = (TagNode) tds.toArray()[10];
					for (Object td10Child : td10.getChildren()) {
						if (td10Child instanceof ContentNode) {
							Float rating;
							try {
								rating = Float.valueOf(nf.parse(
										td10Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								rating = Float.valueOf("0");
							}
							p.setRating(rating);
							break;
						}
					}

					// dotze td
					TagNode td11 = (TagNode) tds.toArray()[11];
					for (Object td11Child : td11.getChildren()) {
						if (td11Child instanceof ContentNode) {
							Float ratingLast3Games;
							try {
								ratingLast3Games = Float.valueOf(nf.parse(
										td11Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								ratingLast3Games = Float.valueOf("0");
							}
							p.setRatingLast3Games(ratingLast3Games);
							break;
						}
					}

					// tretze td
					TagNode td12 = (TagNode) tds.toArray()[12];
					for (Object td12Child : td12.getChildren()) {
						if (td12Child instanceof ContentNode) {
							Float increase15;
							try {
								increase15 = Float.valueOf(nf.parse(
										td12Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								increase15 = Float.valueOf("0");
							}
							p.setIncrease15(increase15);
							break;
						}
					}

					// catorze td
					TagNode td13 = (TagNode) tds.toArray()[13];
					for (Object td13Child : td13.getChildren()) {
						if (td13Child instanceof ContentNode) {
							Float keepPrice;
							try {
								keepPrice = Float.valueOf(nf.parse(
										td13Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								keepPrice = Float.valueOf("0");
							}
							p.setKeepPrice(keepPrice);
							break;
						}
					}

					// quinze td
					TagNode td14 = (TagNode) tds.toArray()[14];
					for (Object td14Child : td14.getChildren()) {
						if (td14Child instanceof ContentNode) {
							Float decrease15;
							try {
								decrease15 = Float.valueOf(nf.parse(
										td14Child.toString().trim()).floatValue());
							} catch (ParseException pe) {
								decrease15 = Float.valueOf("0");
							}
							p.setDecrease15(decrease15);
							break;
						}
					}

				}catch(Exception e){
					Log.d(Supermanager.TAG, "Error...");
				}

				p.setPosition(position);
				players.add(p);
			}
		}
		catch(Exception e)
		{}
		
		return System.nanoTime()-start;
	}
	
	public ArrayList<Player> getPlayers()
	{
		return players;
	}
}
